package com.supinfo.suptracking.dao.jpa;

import com.supinfo.suptracking.dao.InvoiceDao;
import com.supinfo.suptracking.entity.Invoice;
import com.supinfo.suptracking.entity.Invoice_;
import com.supinfo.suptracking.entity.User;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author Fabien, Jérémy, Ludovic, Brice
 */

@Stateless
public class JpaInvoiceDao implements InvoiceDao {

    @PersistenceContext
    private EntityManager em;
    
    @Override
    public void addInvoice(Invoice invoice) {
        em.persist(invoice);
    }

    @Override
    public void delInvoice(Invoice invoice) {
        Long id = invoice.getId();
        em.remove(id);
    }

    @Override
    public List<Invoice> getAllInvoice() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Invoice> query = cb.createQuery(Invoice.class);
        return em.createQuery(query).getResultList();
    }

    @Override
    public List<Invoice> getInvoiceByDate(Date date) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Invoice> query = cb.createQuery(Invoice.class);
        Root<Invoice> invoice = query.from(Invoice.class);
        
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(invoice.get(Invoice_.date), date));
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();
    }

    @Override
    public List<Invoice> getInvoiceByUser(User user) {
        Long userId = user.getId();
        
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Invoice> query = cb.createQuery(Invoice.class);
        Root<Invoice> invoice = query.from(Invoice.class);
        
        List<Predicate> predicates = new ArrayList<>();
        predicates.add(cb.equal(invoice.get(Invoice_.userId), userId));
        
        query.where(predicates.toArray(new Predicate[predicates.size()]));
        
        return em.createQuery(query).getResultList();
    }
}